package cn.com.ddapp.ddm.fragment.base.mine;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.ypy.eventbus.EventBus;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.AlipayListAdapter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.mine.AliPay;
import cn.com.ddapp.ddm.bean.mine.BindSettingActivity;
import cn.com.ddapp.ddm.bean.mine.MyBankInfo;
import cn.com.ddapp.ddm.fragment.base.BaseFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.ui.mine.BindAlipayActivity;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.SPUtils;

/**
 * Created by admin on 2016/8/27.
 */
public class BindAlipayFragment extends BaseFragment {

    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.no_alipay)
    TextView noAlipay;
    @BindView(R.id.alipay_listView)
    SwipeMenuListView alipayListView;


    private List<AliPay.ListBean> list;
    View foot;
    String userId;
    String account;
    int id;
    AlipayListAdapter adapter;
    int orientation;

    @Override
    protected String getFragmentTag() {
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initData() {
        userId = SPUtils.getStringData(getActivity(), SPUtils.USERID);
        if (!NetUtils.isConnected(getActivity())) {
            Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback callback = new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
                    Gson gson = new Gson();
                    AliPay card = gson.fromJson(response, AliPay.class);
                    if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult())) && card.getLogin()) {
                        BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                    } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                        BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                    } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                        if (card.getList().size() == 0) {
                            noAlipay.setVisibility(View.VISIBLE);
                        } else {
                            noAlipay.setVisibility(View.GONE);
                            alipayListView.setVisibility(View.VISIBLE);
                            list = card.getList();
                            AliPay.ListBean aliPay = new AliPay.ListBean();
                            list.add(aliPay);
                            adapter = new AlipayListAdapter(getActivity(),list,orientation);
                            alipayListView.setAdapter(adapter);
                        }
                    }
                }
            };
            //查看绑定卡列表,type  int[N]  1:查看银行卡 2:查看支付宝 查看全部
            OKUtilAPI.post(OKUtilAPI.getCard, "userId=" + userId + "&type=" + 2, callback);
        }

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem defaultItem = new SwipeMenuItem(
                        getContext());
                // set item background 96CEB4
                defaultItem.setBackground(new ColorDrawable(Color.rgb(0x96,
                        0xCE, 0xB4)));
                // set a icon
                defaultItem.setTitle("默认");
                defaultItem.setTitleColor(Color.WHITE);
                if (orientation==0||orientation==2){
                    defaultItem.setTitleSize(25);
                    // set item width
                    defaultItem.setWidth(dp2px(90));
                }else if (orientation==1){
                    defaultItem.setTitleSize(15);
                    // set item width
                    defaultItem.setWidth(dp2px(40));
                }
                // add to menu
                menu.addMenuItem(defaultItem);

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getContext());
                // set item background  FF6F69
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xFF,
                        0x6F, 0x69)));

                // set a icon
                deleteItem.setTitle("删除");
                deleteItem.setTitleColor(Color.WHITE);
                if (orientation==0||orientation==2){
                    deleteItem.setTitleSize(25);
                    // set item width
                    deleteItem.setWidth(dp2px(90));
                }else if (orientation==1){
                    deleteItem.setTitleSize(15);
                    // set item width
                    deleteItem.setWidth(dp2px(40));
                }
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        alipayListView.setMenuCreator(creator);
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        orientation = getActivity().getResources().getConfiguration().orientation;
        EventBus.getDefault().register(this);
        alipayListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                id = list.get(i).getId() ;
                account = list.get(i).getBankAccount();
                Bundle bundle = new Bundle();
                bundle.putString("from","bindAlipayFragment");
                bundle.putInt("id", id);
                bundle.putString("account", account);
                EventBus.getDefault().post(bundle);
                BindSettingActivity.instance.finish();

            }
        });



        alipayListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                //position代表listView中的哪一项，index代表侧滑的哪一项
                if (!NetUtils.isConnected(getActivity())) {
                    Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
                } else {
                    switch (index){
                        //设置默认银行地址
                        case 0 :
                            if (!NetUtils.isConnected(getActivity())) {
                                Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
                            } else {
                                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                                OkUtilCallback callback = new OkUtilCallback(mEmptyLayout) {
                                    @Override
                                    public void onMyResponse(String response, int id) {
                                        Gson gson = new Gson();
                                        AliPay card = gson.fromJson(response, AliPay.class);
                                        if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult())) && card.getLogin()) {
                                            BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                        } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                            BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                        } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                            BaseApplication.getIntstance().showToast("已设为默认项", Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                            adapter.setOld(true);
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                };
                                /*设置默认银行地址
                                userId  int[Y] 会员ID
                                id  int[Y] 会员银行/支付宝的ID*/
                                OKUtilAPI.post(OKUtilAPI.udefaultBank, "userId=" + userId + "&id=" + list.get(position).getId(), callback);
                                Log.e("111", "id=" + list.get(position).getId());
                            }
                            break;
                        //删除
                        case  1 :
                            final Dialog dialog = new Dialog(getActivity(),R.style.FullScreenDialog);
                            View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_detele,null);
                            dialog.setContentView(view1);
                            dialog.setCanceledOnTouchOutside(true);
                            Button negativeBt = (Button) view1.findViewById(R.id.negative);
                            Button okBt = (Button) view1.findViewById(R.id.ok);
                            okBt.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (!NetUtils.isConnected(getActivity())) {
                                        Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
                                    } else {
                                        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                                        OkUtilCallback callback = new OkUtilCallback(mEmptyLayout) {
                                            @Override
                                            public void onMyResponse(String response, int id) {
                                                Gson gson = new Gson();
                                                AliPay card = gson.fromJson(response, AliPay.class);
                                                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult())) && card.getLogin()) {
                                                    BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                                } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                                    BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                                    BaseApplication.getIntstance().showToast("已删除", Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                                    list.remove(position);
                                                    if (list.size() == 1) {
                                                        noAlipay.setVisibility(View.VISIBLE);
                                                        list.clear();
                                                    }
                                                    adapter.setOld(true);
                                                    adapter.notifyDataSetChanged();
                                                    dialog.dismiss();
                                                }
                                            }
                                        };
                                        //删除银行卡/支付宝,"userId int[Y] 会员ID  id [Y] 要删除的ID"
                                        OKUtilAPI.post(OKUtilAPI.del, "userId=" + userId + "&id=" + list.get(position).getId(), callback);
                                    }
                                }
                            });
                            negativeBt.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    adapter.setOld(true);
                                    adapter.notifyDataSetChanged();
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                            break;
                    }
                }
                return false;
            }
        });

        //侧滑状态改变时
        alipayListView.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
            @Override
            public void onMenuOpen(int position) {
            }

            @Override
            public void onMenuClose(int position) {
                adapter.setMySoothClosePosit(position);//某一条恢复原状
                adapter.setMySoothAlterPosit(-1);
            }
        });

        //滑动监听，滑动开始和结束
        alipayListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
            @Override
            public void onSwipeStart(int position) {
                adapter.setOld(false);//可以改变背景
                adapter.setMySoothAlterPosit(position);//某一条改变背景,不能放在上面的onMenuOpen()中
                adapter.setMySoothClosePosit(-1);
            }

            @Override
            public void onSwipeEnd(int position) {

            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_bind_alipay;
    }

    @OnClick({R.id.no_alipay,R.id.img_error_layout})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.no_alipay:
                intent = new Intent(getActivity(), BindAlipayActivity.class);
                startActivity(intent);
                break;
            case R.id.img_error_layout:
                initData();
                break;
        }
    }


    public void onEventMainThread(MyBankInfo info) {
        if (info.getKey().equals("bank")){
            alipayListView.smoothCloseMenu();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
